//
//  DDLoginRootVC.m
//  dingdang
//
//  Created by Jiangxp on 15/6/29.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDLoginRootVC.h"
#import "GlobalDefine.h"
#import "DDNetWorkAPIClient.h"
#import "MainViewController.h"
#import "DDForgetPWVC.h"
#import "DDRegisterVC.h"
#import "StringUtil.h"
#import "UICommonFunc.h"
#import "DDThirdPartyLogin.h"
#import "DateUtil.h"
#import "WeiboUser.h"

#import "WeiboSDK.h"
#import "NSString+MD5.h"
#import "AppDelegate.h"
@interface DDLoginRootVC ()
{
    TencentOAuth *tencentOAuth;
    BOOL isThirdPartLogin;
    ABCIntroView *introView;
}

@end

@implementation DDLoginRootVC

- (void)createUI
{
    // Do any additional setup after loading the view from its nib.
    //是否安装了qq
    _qqLoginBtn.hidden = ![QQApiInterface isQQInstalled];
    //是否安装了微博
    _weiboLoginBtn.hidden = ![WeiboSDK isWeiboAppInstalled];
    //是否安装了微信
    _weixinLoginBtn.hidden = ![WXApi isWXAppInstalled];
    //微信登录还未申请通过

    
    DDSharedUser *user = [DDSharedUser shared];
    _phoneNum.text = [user userDefaultValueForKey:kUsername];
    _password.text = [user userDefaultValueForKey:kPassword];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    //自定义TAB BAR UI
    [self addNavigatorTitle:NSLocalizedString(@"登  录", nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    
    self.login_bg_view.layer.cornerRadius = 10;
    self.autonLogin.selected = YES;
}

-(void)createData
{
    isThirdPartLogin = NO;
}

- (void)viewDidLoad {
    
    NSLog(@"进入到------>DDLoginRootVC");
    [super viewDidLoad];
   
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![[defaults objectForKey:@"intro_screen_viewed"] boolValue]) {
        introView = [[ABCIntroView alloc] initWithFrame:self.view.bounds];
        introView.delegate = self;
        introView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:introView];
    }else{
        [self createUI];
        [self createData];
    }
}

-(void)onDoneButtonPressed{
    [UIView animateWithDuration:1.0 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        introView.alpha = 0;
    } completion:^(BOOL finished) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setValue:[NSNumber numberWithBool:YES] forKey:@"intro_screen_viewed"];
        [introView removeFromSuperview];
    }];
    [self createUI];
    [self createData];
}

- (IBAction)userLogin:(id)sender {
    if ([StringUtil isEmptyString:_phoneNum.text ]) {
        [UICommonFunc showAlert:@"请输入登录账号！"];
        return;
    }
    if (_password.text.length > 14 || _password.text.length < 6) {
        [UICommonFunc showAlert:@"请输入您的6-14位密码！"];
        return;
    }
    
    DDSharedUser *user = [DDSharedUser shared];
    [user updateUserDefaults:_phoneNum.text forKey:kUsername];
    [user updateUserDefaults:_password.text forKey:kPassword];
    
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [network userAuthToken:_phoneNum.text password:_password.text CompletionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        //    [network userAuthToken:@"test01" password:@"a123456" CompletionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        if (!isSuccess) {
            NSError *err = (NSError *)message;
            if (err.code == -1011) {
                [UICommonFunc showAlert:@"用户名或密码错误！"];
            }else {
                [UICommonFunc showAlert:@"登录不了哦，再试试看！"];
            }
            return;
        }
        DDSharedUser *sharedUser = [DDSharedUser shared];
        [network getUserInfo:(NSString *)sharedUser.access_token completionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
            if (!isSuccess) {
                [UICommonFunc showAlert:@"登录不了哦，再试试看！"];
                return;
            }
            MainViewController *viewController = [[MainViewController alloc] init];
            UINavigationController*nav = [[UINavigationController alloc] initWithRootViewController:viewController];
            nav.navigationBar.hidden = YES;
            AppDelegate *pDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [pDelegate.window setRootViewController:nav];
            
            DDSharedUser *user = [DDSharedUser shared];
            [user updateUserDefaults:_phoneNum.text forKey:kUsername];
            [user updateUserDefaults:_password.text forKey:kPassword];
        }];
    }];
}

- (IBAction)forgetPW:(id)sender {
    DDForgetPWVC *viewController = [[DDForgetPWVC alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (IBAction)regisNow:(id)sender {
    DDRegisterVC *viewController = [[DDRegisterVC alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (IBAction)qqLogin:(id)sender {
    //第三方登录QQ
    tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQ_AppId andDelegate:self];
    tencentOAuth.redirectURI = @"";
    NSArray *premissions = [NSArray arrayWithObjects:@"get_user_info", @"get_simple_userinfo", @"add_t",nil];
    
    NSLog(@"premissions=====%@",premissions);
    [tencentOAuth authorize:premissions inSafari:NO];
    NSLog(@"[tencentOAuth authorize:premissions inSafari:NO]=====%@",[tencentOAuth authorize:premissions inSafari:NO]?@"YES":@"NO");
}

/**
 * QQ：登录成功后的回调
 */
- (void)tencentDidLogin
{
    NSLog(@"tencentOAuth.openId=====%@,tencentOAuth.accessToken======%@",tencentOAuth.openId,tencentOAuth.accessToken);
    NSLog(@"[DateUtil DateFormat:tencentOAuth.expirationDate]=====%@",[DateUtil DateFormat:tencentOAuth.expirationDate]);
    
    if (tencentOAuth.accessToken && 0!= [tencentOAuth.accessToken length]) {
        [DDThirdPartyLogin shared].QQ_accessToken = tencentOAuth.accessToken;
        [DDThirdPartyLogin shared].QQ_expirationDate = [DateUtil DateFormat:tencentOAuth.expirationDate];
        [DDThirdPartyLogin shared].QQ_openId = tencentOAuth.openId;
        if (![tencentOAuth getUserInfo]) {
            NSLog(@"获取个人信息失败");
        };
    }else {
        NSLog(@"qqLoginError:%@", tencentOAuth.accessToken);
    }
    [UICommonFunc showHideLoadingView:YES];
}
/**
 * QQ：登录成功后的回调后，调用此方法
 */
- (void)getUserInfoResponse:(APIResponse*) response
{
    [UICommonFunc showHideLoadingView:NO];
    NSDictionary *jsonResponse = response.jsonResponse;
    [DDThirdPartyLogin shared].QQ_nickName = [jsonResponse objectForKey:@"nickname"];
    [DDThirdPartyLogin shared].QQ_headUrl_40 = [jsonResponse objectForKey:@"figureurl_qq_1"];
    [DDThirdPartyLogin shared].QQ_headUrl_100 = [jsonResponse objectForKey:@"figureurl_qq_2"];
    [DDThirdPartyLogin shared].QQ_gender = [jsonResponse objectForKey:@"gender"];
    [self thirdPartyLogin:@"QQ"];
}

- (IBAction)weiboLogin:(id)sender {
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = SINA_kRedirectURI;
    request.scope = @"all";
    request.userInfo = @{@"NOTIFY": NOTIFY_WEIBO_LOGIN};
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(weiboLoginResponse:)
                                                 name:NOTIFY_WEIBO_LOGIN
                                               object:nil];
    [WeiboSDK sendRequest:request];
}

- (void)weiboLoginResponse:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:notification.name object:nil];
    WBAuthorizeResponse *baseResponse = (WBAuthorizeResponse *)notification.object;
    if ([baseResponse statusCode] == WeiboSDKResponseStatusCodeSuccess) {   //成功
        [DDThirdPartyLogin shared].WEIBO_accessToken = [baseResponse accessToken];
        [DDThirdPartyLogin shared].WEIBO_userID = [baseResponse userID];
        [DDThirdPartyLogin shared].WEIBO_expirationDate = [DateUtil DateFormat:[baseResponse expirationDate]];
        [DDThirdPartyLogin shared].WEIBO_refreshToken = [baseResponse refreshToken];
//        [WBHttpRequest requestForUserProfile:[DDThirdPartyLogin shared].WEIBO_userID withAccessToken:[DDThirdPartyLogin shared].WEIBO_accessToken andOtherProperties:nil queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
//            if (!error)
//            {
//                WeiboUser *weiboUser = (WeiboUser *)result;
//                [DDThirdPartyLogin shared].WEIBO_name = weiboUser.name;
//                [DDThirdPartyLogin shared].WEIBO_headUrl_50 = weiboUser.profileImageUrl;
//                [DDThirdPartyLogin shared].WEIBO_headUrl_180 = weiboUser.avatarHDUrl;
//                [DDThirdPartyLogin shared].WEIBO_gender = weiboUser.gender;
//                [self thirdPartyLogin:@"WEIBO"];
//            }
//            NSLog(@"微博requestForUserProfile失败");
//        }];
    }else{
        NSLog(@"微博请求发送失败");
    }
}

- (IBAction)weixinLogin:(id)sender {
    SendAuthReq* req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_message,snsapi_userinfo,snsapi_friend,snsapi_contact"; // @"post_timeline,sns"
    req.state = NOTIFY_WEIXIN_LOGIN;
    req.openID = WEIXIN_AppSecret;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(weixinLoginResponse:)
                                                 name:NOTIFY_WEIXIN_LOGIN
                                               object:nil];
    
    //[WXApi sendAuthReq:req viewController:self delegate:nil];
    //[WXApi sendResp:req];
    [WXApi safeSendReq:req];
}

- (void)weixinLoginResponse:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:notification.name object:nil];
    NSDictionary *response = notification.object;
    
}

- (void)thirdPartyLogin:(NSString*)thirdPartyLogin_source
{
    [self showHUD:@"登录中"];
    NSString *accessToken, *openId, *nickName, *expirationDate, *avatarUrl;
    if ([thirdPartyLogin_source isEqualToString:@"QQ"]) {
        accessToken = [DDThirdPartyLogin shared].QQ_accessToken;
        openId = [DDThirdPartyLogin shared].QQ_openId;
        nickName = [DDThirdPartyLogin shared].QQ_nickName;
        expirationDate = [DDThirdPartyLogin shared].QQ_expirationDate;
        avatarUrl = [DDThirdPartyLogin shared].QQ_headUrl_100;
    }else if([thirdPartyLogin_source isEqualToString:@"WEIBO"]){
        accessToken = [DDThirdPartyLogin shared].WEIBO_accessToken;
        openId = [DDThirdPartyLogin shared].WEIBO_userID;
        nickName = [DDThirdPartyLogin shared].WEIBO_name;
        expirationDate = [DDThirdPartyLogin shared].WEIBO_expirationDate;
        avatarUrl = [DDThirdPartyLogin shared].WEIBO_headUrl_180;
    }else if([thirdPartyLogin_source isEqualToString:@"WEIXIN"]){
        
        
    }
    NSLog(@"openId================%@",openId);
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [network getSystime:^(BOOL isSuccess, NSString *message, NSString *status, id object) { //获取系统时间
        NSString *dataStr;
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"yyMMdd"];
        if(isSuccess){
            //NSLog(@"Login:获取系统时间成功！");
            double unixTimeStamp = [[object objectForKey:@"time"] doubleValue]/1000;
            NSTimeInterval _interval=unixTimeStamp;
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
            [dateformatter setLocale:[NSLocale currentLocale]];
            dataStr = [dateformatter stringFromDate:date];
        }else{
            //NSLog(@"Login:获取系统时间失败，使用本地时间！");
            NSDate *date = [NSDate date];
            dataStr = [dateformatter stringFromDate:date];
        }
        NSString *password_TH = [self getThirdPartyLogin_Password:openId date:dataStr];
        //判断是否绑定
        //NSLog(@"Login:判断是否绑定用户！");
        [network isBind:thirdPartyLogin_source accessToken:accessToken completionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
            if (!isSuccess) {
                [UICommonFunc showAlert:@"失败"];
                [self hideHUD];
                return ;
            }
            NSLog(@"isBind:dict=====%@",dict);
            NSLog(@"[dict objectForKey:@result]=====%@",[dict objectForKey:@"result"]);
            if (![[dict objectForKey:@"result"] boolValue]) {
                //NSLog(@"Login:未绑定用户－>判断是否是已注册用户！");
                NSLog(@"未绑定,openId================%@",openId);
                [network isOpen:openId CompletionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
                    if (!isSuccess){ [self hideHUD]; return; }
                    
                    if (![[dict objectForKey:@"result"] intValue]) {
                        NSLog(@"Login:未注册用户，用户注册！openId===%@",openId);
                        [network userRegister:openId phoneCode:@"" password:@"123456" nickName:nickName fid:nil completionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
                            if (!isSuccess) {
                                NSLog(@"Login:未注册用户首次注册，注册失败！");
                                [self hideHUD];
                                [UICommonFunc showAlert:message];
                                return ;
                            }
                            NSLog(@"Login:用户首次注册，注册成功！");
                            NSLog(@"Login:新注册用户->用户登录！");
                            [network userAuthToken:openId password:password_TH CompletionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
                                if (!isSuccess) {
                                    NSLog(@"Login:使用openId登录失败！");
                                    [self hideHUD];
                                    [UICommonFunc showAlert:@"登录失败！"];
                                    return;
                                }
                                DDSharedUser *user = [DDSharedUser shared];
                                [user updateUserDefaults:openId forKey:kUsername];
                                [user updateUserDefaults:password_TH forKey:kPassword];
                                user.userInfo.avatarUrl = avatarUrl;
                                user.userInfo.nickName = nickName;
                                NSLog(@"Login:登录成功－>绑定用户！");
                                [network bindAccountd:user.access_token openId:openId nickName:nickName accessToken:accessToken source:thirdPartyLogin_source validity:expirationDate completionBlock:^(BOOL isSuccess, NSString *message, NSString *status) {
                                    if (!isSuccess) {
                                        NSLog(@"Login:绑定第三方账号失败！");
                                        [self hideHUD];
                                        [UICommonFunc showAlert:@"登录失败！"];
                                        return;
                                    }
                                    [self hideHUD];
                                    //NSLog(@"Login:绑定第三方账号成功！");
                                    //NSLog(@"Login:使用openId登录成功！");
                                    MainViewController *viewController = [[MainViewController alloc] init];
                                    UINavigationController*nav = [[UINavigationController alloc] initWithRootViewController:viewController];
                                    nav.navigationBar.hidden = YES;
                                    AppDelegate *pDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                                    [pDelegate.window setRootViewController:nav];
                                    return;
                                }];
                            }];
                        }];
                    }else {
                         NSLog(@"Login:已注册用户->用户登录！openId====%@",openId);
                        [network userAuthToken:openId password:password_TH CompletionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
                            if (!isSuccess) {
                                NSLog(@"Login:使用openId登录失败！");
                                [self hideHUD];
                                [UICommonFunc showAlert:@"登录失败！"];
                                return;
                            }
                            DDSharedUser *user = [DDSharedUser shared];
                            [user updateUserDefaults:openId forKey:kUsername];
                            [user updateUserDefaults:password_TH forKey:kPassword];
                            user.userInfo.avatarUrl = avatarUrl;
                            user.userInfo.nickName = nickName;
                            //NSLog(@"Login:登录成功－>绑定用户！");
                            [network bindAccountd:user.access_token openId:openId nickName:nickName accessToken:accessToken source:thirdPartyLogin_source validity:expirationDate completionBlock:^(BOOL isSuccess, NSString *message, NSString *status) {
                                if (!isSuccess) {
                                    NSLog(@"Login:绑定第三方账号失败！");
//                                  return;
                                }else{
                                    NSLog(@"Login:使用openId登录成功！");
                                }
                                //NSLog(@"Login:绑定第三方账号成功！");
                                //
                                [self hideHUD];
                                MainViewController *viewController = [[MainViewController alloc] init];
                                UINavigationController*nav = [[UINavigationController alloc] initWithRootViewController:viewController];
                                nav.navigationBar.hidden = YES;
                                AppDelegate *pDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                                [pDelegate.window setRootViewController:nav];
                                return;
                            }];
                        }];
                    }
                }];
            } else {
                NSLog(@"Login:已绑定用户登录！openId======%@",openId);
                [network userAuthToken:openId password:password_TH CompletionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
                    if (!isSuccess) {
                        //NSLog(@"Login:使用openId登录失败！");
                        [self hideHUD];
                        [UICommonFunc showAlert:@"登录失败！"];
                        return;
                    }
                    [self hideHUD];
                    //NSLog(@"Login:使用openId登录成功！");
                    MainViewController *viewController = [[MainViewController alloc] init];
                    UINavigationController*nav = [[UINavigationController alloc] initWithRootViewController:viewController];
                    nav.navigationBar.hidden = YES;
                    AppDelegate *pDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                    [pDelegate.window setRootViewController:nav];
                    
                    DDSharedUser *user = [DDSharedUser shared];
                    [user updateUserDefaults:openId forKey:kUsername];
                    [user updateUserDefaults:password_TH forKey:kPassword];
                    user.userInfo.avatarUrl = avatarUrl;
                    user.userInfo.nickName = nickName;
                    NSLog(@"user.userInfo.uid==============%@",user.userInfo.uid);
                    NSLog(@"user.userInfo.nickName==============%@",user.userInfo.nickName);
                    
                }];
            }
        }];
    }];
}

/**
 * QQ：登录失败后的回调
 * \param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled) {
        NSLog(@"用户取消登录");
    }else{
        NSLog(@"登录失败");
    }
}

/**
 * QQ：登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork
{
    NSLog(@"网络连接失败，登录不成功");
}

//password：md5(yyMMdd+用户名倒序+26%trUst#9527)
//*       其中：yyMMdd从服务端接口【/api/systime】获取
- (NSString *)getThirdPartyLogin_Password:(NSString *)userName date:(NSString*)dataStr{
    NSString *reverseUserName = [StringUtil reverseString:userName];
    NSString *tmp = @"26%trUst#9527";
    return [[NSString stringWithFormat:@"%@%@%@", dataStr, reverseUserName, tmp] MD5];
}

- (IBAction)clickBackground:(id)sender {
    [sender endEditing:YES];
}
- (IBAction)autoLoginAction:(UIButton *)sender {
    sender.selected = !sender.selected;
}

@end
